/**
 * 				Client.java
 *				------------
 *		
 *   Author:	bin04017
 *   ID:		bin04017
 *	 Created:	24.01.2007
 *	 Project:	Mochito
 *	 Package:	tools.clientPackage.client
 *	 Usage:		
 */
package mochito.tools.clientPackage.client;

import java.io.IOException;

import mochito.tools.clientPackage.sender.Sender;
import mochito.tools.clientPackage.systray.ClientSystray;
import mochito.tools.clipboard.AccessClipboard;
import mochito.tools.syshook.Syshook;

/**
 * @author bin04017
 * 
 */
public class Client implements Runnable {

	private Integer port = 2007;

	private String host = null;

	private ClientSystray clientSystray = null;
	
	private Syshook syshook = new Syshook();

	private String msgOld = null;

	private boolean running = true;

	public Client(String host, ClientSystray clientSystray) {
		this.host = host;
		this.clientSystray = clientSystray;
	}

	public Client(String host, Integer port, ClientSystray clientSystray) {
		this.host = host;
		this.port = port;
		this.clientSystray = clientSystray;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		while (running) {
			if (clientSystray.getRunning()) {
				String msgNew = AccessClipboard.getClipboard();
				try {
					if (msgOld == null || !msgOld.endsWith(msgNew)) {
						Sender.send(host, port, msgNew);
						msgOld = msgNew;
					}
				} catch (IOException e1) {
					e1.printStackTrace();
				}

				try {
					Thread.sleep(4000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			if(clientSystray.isCTRLc()){
				if(syshook.getPressedSinceLastCheck()){
					String msg = AccessClipboard.getClipboard();
					try {
						Sender.send(host, port, msg);
					} catch (IOException e1) {
						e1.printStackTrace();
					} finally {
						clientSystray.setSingle(false);
					}
				}
			}
			if (clientSystray.isSingle()) {
				String msg = AccessClipboard.getClipboard();
				try {
					Sender.send(host, port, msg);
				} catch (IOException e1) {
					e1.printStackTrace();
				} finally {
					clientSystray.setSingle(false);
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @return the running
	 */
	public boolean isRunning() {
		return running;
	}

	/**
	 * @param running
	 *            the running to set
	 */
	public void stop() {
		this.running = false;
	}

}
